﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using ImageDomain.DE;
using itk.simple;
using Newtonsoft.Json.Linq;

namespace ImageDomain.Utils;
public static class ImageConvertUtil
{
    /// <summary>
    /// 将 simpleitk image 转化为 byte 数组
    /// </summary>
    /// <param name="itkImage"></param>
    /// <returns></returns>
    public static byte[] ConvertImageToByte(this IImage3d image3d)
    {
        var size = image3d.ItkImage!.GetSize();
        var len = 1;
        for (var dim = 0; dim < image3d.ItkImage!.GetDimension(); dim++)
        {
            len *= (int)size[dim];
        }
        var buffer = image3d.ItkImage!.GetBufferAsInt32();
        var result = new int[len];
        Marshal.Copy(buffer, result, 0, len);

        var byteArray = new byte[result.Length * sizeof(int)];
        Buffer.BlockCopy(result, 0, byteArray, 0, byteArray.Length);

        return byteArray;
    }


    public static Image ConvertBytesToImage(this byte[][][] imageArray, uint[] size)
    {
        // 创建 SimpleITK Image 对象
        var image = new Image(size[0], size[1], size[2], PixelIDValueEnum.sitkInt8);

        // 填充 Image 数据
        for (var z = 0; z < size[2]; z++)
        {
            for (var y = 0; y < size[1]; y++)
            {
                for (var x = 0; x < size[0]; x++)
                {
                    image.SetPixelAsInt8(new VectorUInt32() { (uint)x, (uint)y, (uint)z }, (sbyte)imageArray[z][y][x]);
                }
            }
        }
        return image;
    }


    public static byte[][][] ConvertToByteArr(this string base64Str, uint[] size)
    {
        // 定义width、height、count
        var width = size[0];
        var height = size[1];
        var count = size[2];

        // 将Base64字符串解码为字节数组
        byte[] byteArray = Convert.FromBase64String(base64Str);

        // 创建三维数组
        byte[][][] result = new byte[count][][];
        for (int i = 0; i < count; i++)
        {
            result[i] = new byte[height][];
            for (int j = 0; j < height; j++)
            {
                result[i][j] = new byte[width];
            }
        }

        // 填充三维数组
        int index = 0;
        for (int i = 0; i < count; i++)
        {
            for (int j = 0; j < height; j++)
            {
                for (int k = 0; k < width; k++)
                {
                    if (index < byteArray.Length)
                    {
                        result[i][j][k] = byteArray[index++];
                    }
                    else
                    {
                        // 如果 Base64 字符串不足以填充整个数组，可以选择用0或其他值填充
                        result[i][j][k] = 0;
                    }
                }
            }
        }

        return result;

    }

}
